//
//  YZEConsultViewController.m
//  yilutongxing
//
//  Created by T&J on 2017/11/10.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import <UIColor+QMUI.h>
#import "YZEConsultViewController.h"
#import "CommonDefine.h"
#import "PYSearchViewController.h"
#import "RPUserDoctorInfo.h"
#import "DoctorSearchSuggestionCell.h"
#import "YZEDoctorDetailViewController.h"
#import "MyFansTableViewCell.h"
#import "zhuShouViewController.h"
#import "ConsultViewController.h"
#import "AppDelegate.h"
#import "DGTTabBarController.h"
#import "TimeTools.h"
#import "YZEDoctorDetailViewController.h"

#define URL_alldoctors @"/api/doctors/notkick?page=0&size=1000000"
#define URL_Followho @"/api/follow"
//获取与“专家解答”的最后一条消息
#define URL_lastalk2support @"/api/messages/lastest/1/SYSTEM_MESSAGE/"
#define URL_Getdoctorinfo @"/api/doctors/"

@interface YZEConsultViewController ()<UITableViewDelegate, UITableViewDataSource,
                                        PYSearchViewControllerDataSource, PYSearchViewControllerDelegate,
                                        MyFansCellDelegate>
//UI
@property (strong, nonatomic) IBOutlet UIView *blue_head_bg;
@property (strong, nonatomic) IBOutlet UIView *customer_service_bg;
@property (strong, nonatomic) IBOutlet UILabel *last_chat_time;
@property (strong, nonatomic) IBOutlet UILabel *last_chat_text;
@property (strong, nonatomic) IBOutlet UITableView *funs_tableView;
@property (strong, nonatomic) IBOutlet UIButton *lookup_doctor_btn;
@property (strong, nonatomic) IBOutlet UIView *badge;
@property (strong, nonatomic) IBOutlet UILabel *badge_label;
//数据
@property (strong, nonatomic) NSMutableArray *funs_arr;//关注的医生列表

@property (nonatomic, strong) NSArray *doctorArr;
@property (nonatomic, strong) NSMutableArray *tobeChoosenArr;
@end

@implementation YZEConsultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.m_labelTitle.textColor = WHITE_COLOR;
    self.m_labelTitle.text = @"咨询与回答";
    [self.navibar_bottom_line removeFromSuperview];
    
    [self initUI];
    
    
    //请求专家最近一次解答
    //NSDictionary *pra = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"uid", @"SYSTEM_MESSAGE",@"model", nil];
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_lastalk2support]
                                      parameters:nil
                                        delegate:self
                                      requestTag:2
                                    successBlock:^(id responseObject)
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
        NSDate *d = [dateFormatter dateFromString:responseObject[@"createdDate"]];
        self.last_chat_time.text = [TimeTools getYearMonthDayHourMinWithDate:d];
        if ([responseObject[@"type"] compare:@"text"]==0) {
            self.last_chat_text.text = responseObject[@"content"];
        }
        if ([responseObject[@"type"] compare:@"image"]==0) {
            self.last_chat_text.text = @"[图片]";
        }
    }];
    //请求关注的医生列表
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_Followho]
                                      parameters:nil
                                        delegate:self
                                      requestTag:1
                                    successBlock:^(id responseObject)
    {
        self.funs_arr = responseObject;
        [self.funs_tableView reloadData];
    }];
    dispatch_async(GLOBAL_BG_QUEUE, ^{
        [self sendDoctorsReq];
    });
}

- (void)viewWillAppear:(BOOL)animated{
    DGTTabBarController *tabBarController = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).tabBarController;
    //请求未读消息数
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:@"/api/message-boxes/unreadCount/SYSTEM_MESSAGE"]
                                       parameters:nil
                                         delegate:self
                                       requestTag:1
                                     successBlock:^(id responseObject)
     {
         NSNumber *p_count = (NSNumber*)responseObject;
         long count = [p_count longValue];
         if (count>0) {
             [tabBarController setBadgeWithString:@"" toIndex:3];
             self.badge.hidden = NO;
             self.badge_label.text = [p_count stringValue];
         }
         else {
             self.badge.hidden = YES;
             [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:@"/api/message-boxes/unreadCount/CONSULTATION_MESSAGE"]
                                                parameters:nil
                                                  delegate:self
                                                requestTag:2
                                              successBlock:^(id responseObject)
              {
                  NSNumber *p_count = (NSNumber*)responseObject;
                  long count = [p_count longValue];
                  if (count>0) {
                      [tabBarController setBadgeWithString:@"" toIndex:3];
                  }
                  else {
                      [tabBarController setBadgeWithString:nil toIndex:3];
                  }
              }];
         }
     }];
    //请求关注的医生列表
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_Followho]
                                      parameters:nil
                                        delegate:self
                                      requestTag:1
                                    successBlock:^(id responseObject)
     {
         self.funs_arr = responseObject;
         [self.funs_tableView reloadData];
     }];
}

- (void)initUI{
    CGRect frame = self.blue_head_bg.bounds;
    UIImageView *bg = [[UIImageView alloc]initWithFrame:frame];
    [bg setImage:[UIImage imageNamed:@"consult_head_bg"]];
    [self.blue_head_bg addSubview:bg];
    
    //在线客服
    UIGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goCustomerService)];
    [self.customer_service_bg addGestureRecognizer:tap];
    
    //关注的医生列表
    self.funs_tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.funs_tableView.dataSource = self;
    self.funs_tableView.delegate = self;
    
    [self.lookup_doctor_btn addTarget:self action:@selector(goSearchDoctor) forControlEvents:UIControlEventTouchUpInside];
    
    [self.funs_tableView registerNib:[UINib nibWithNibName:@"MyFansTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"fansCell"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UI逻辑
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)goCustomerService{
    zhuShouViewController *vc = [zhuShouViewController new];
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:navi animated:YES completion:nil];
}

#pragma mark - UITableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.funs_arr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //关注的医生列表数据填充
    MyFansTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fansCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    if (self.funs_arr.count > 0) {
        NSDictionary *doctor = self.funs_arr[indexPath.row][@"message"];
        [cell.headImageView sd_setImageWithURL:doctor[@"dReceiver"][@"avatar"]];
        cell.nameLable.text = doctor[@"dReceiver"][@"firstName"];
        cell.contentLable.text = doctor[@"content"];
        cell.sendTime.text = doctor[@"createdDate"];
        cell.tag = [self.funs_arr[indexPath.row][@"doctorId"] integerValue];
        NSNumber *p_count = self.funs_arr[indexPath.row][@"unreadCount"];
        //p_count = [NSNumber numberWithLong:arc4random()%50];//测试数据
        long count = [p_count longValue];
        if (count>0) {
            [cell showBadge:[p_count stringValue]];
        }
        else {
            [cell showBadge:nil];
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ConsultViewController *cVC =[ConsultViewController new];
    NSDictionary *doctor = self.funs_arr[indexPath.row][@"message"];
    cVC.doctorUID = [doctor[@"dReceiver"][@"id"] longValue];
    cVC.doctorName = doctor[@"dReceiver"][@"firstName"];
    cVC.doctorID = [self.funs_arr[indexPath.row][@"doctorId"] longValue];
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:cVC];
    [self presentViewController:navi animated:YES completion:nil];
}

#pragma mark - PYSearchViewControllerDataSource  搜索界面
-(UITableViewCell*)searchSuggestionView:(UITableView *)searchSuggestionView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RPUserDoctorInfo *doctor = self.tobeChoosenArr[indexPath.row];
    static NSString *idenitfier = @"SearchSuggestionCell";
    DoctorSearchSuggestionCell *cell = [searchSuggestionView dequeueReusableCellWithIdentifier:idenitfier];
    if (!cell) {
        [searchSuggestionView registerNib:[UINib nibWithNibName:@"DoctorSearchSuggestionCell" bundle:nil] forCellReuseIdentifier:idenitfier];
        cell = [searchSuggestionView dequeueReusableCellWithIdentifier:idenitfier];
    }
    [cell.avatarbox sd_setImageWithURL:[NSURL URLWithString:doctor.userResponseDto.avatar]];
    cell.doctorName.text = doctor.userResponseDto.firstName;
    cell.hospitalName.text = doctor.hospitalDTO.name;
    cell.zhiChen.text = doctor.professionalTitle;
    cell.menzhenTime.text = doctor.workTime;
    NSString *goodat = [[NSString alloc]init];
    NSMutableArray *gnArr = [[NSMutableArray alloc]init];
    for (RPGrafting *grafting in doctor.graftings) {
        [gnArr addObject:grafting.name];
    }
    goodat = [gnArr componentsJoinedByString:@","];
    cell.goodat.text = goodat;
    
    return cell;
}

- (NSInteger)searchSuggestionView:(UITableView *)searchSuggestionView numberOfRowsInSection:(NSInteger)section{
    return self.tobeChoosenArr.count;
}

- (NSInteger)numberOfSectionsInSearchSuggestionView:(UITableView *)searchSuggestionView{
    return 1;
}

-(CGFloat)searchSuggestionView:(UITableView *)searchSuggestionView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 127;
}

- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)searchBar searchText:(NSString *)searchText{
    if (searchText.length>0 && ![searchText isEqualToString:@" "]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tobeChoosenArr removeAllObjects];
            for (RPUserDoctorInfo *doctor in self.doctorArr) {
                if (doctor.userResponseDto
                    && doctor.userResponseDto.firstName
                    && [doctor.userResponseDto.firstName rangeOfString:searchText].location!=NSNotFound) {
                    [self.tobeChoosenArr addObject:doctor];
                }
            }
            [searchViewController.searchSuggestionView reloadData];
        });
    }
    else {
        self.tobeChoosenArr = [self.doctorArr mutableCopy];
        [searchViewController.searchSuggestionView reloadData];
    }
}

- (void)searchViewController:(PYSearchViewController *)searchViewController didSelectSearchSuggestionAtIndexPath:(NSIndexPath *)indexPath searchBar:(UISearchBar *)searchBar{
    RPUserDoctorInfo *doctor = self.tobeChoosenArr[indexPath.row];
    YZEDoctorDetailViewController *v = [YZEDoctorDetailViewController new];
    v.data = doctor;
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:v];
    [searchViewController presentViewController:navi animated:YES completion:nil];
}

#pragma mark - 业务逻辑
/**
 *搜索医生
 */
-(void)goSearchDoctor{
    //创建控制器
    PYSearchViewController *searchViewController = [PYSearchViewController
                                                    searchViewControllerWithHotSearches:nil
                                                    searchBarPlaceholder:NSLocalizedString(@"搜索医生",@"搜索类型")
                                                    didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText)
                                                    {
                                                        
                                                    }];
    // 4. 设置代理
    searchViewController.delegate = self;
    searchViewController.dataSource = self;
    searchViewController.showSearchHistory = NO;
    [searchViewController setSearchSuggestionHidden:NO];
    searchViewController.cancelButton.tintColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1];
    searchViewController.cancelButton.title = @"取消";
    
    // 5. 跳转到搜索控制器
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    
    [self presentViewController:nav animated:YES completion:^{
        [searchViewController showSuggestionWhenLoaded];
    }];
}
/*
 *请求医生列表
 */
-(void)sendDoctorsReq{
    //请求所有医生
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_alldoctors] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        self.doctorArr = [RPUserDoctorInfo mj_objectArrayWithKeyValuesArrayAdd:responseObject];
        self.tobeChoosenArr = [NSMutableArray arrayWithArray:self.doctorArr];
    }];
}

#pragma mark - cell代理
- (void)OnAvatarClicked:(NSInteger)tag{
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingFormat:@"%@%ld", URL_Getdoctorinfo, (long)tag] parameters:nil delegate:self requestTag:2 successBlock:^(id responseObject) {
        RPUserDoctorInfo *doctorInfo = [RPUserDoctorInfo mj_objectWithKeyValuesAdd:responseObject];
        YZEDoctorDetailViewController *v = [YZEDoctorDetailViewController new];
        v.data = doctorInfo;
        UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:v];
        [self presentViewController:navi animated:YES completion:nil];
    }];
}

#pragma mark - 数据配置
- (NSMutableArray *)funs_arr{
    if (!_funs_arr) {
        _funs_arr = [NSMutableArray array];
    }
    return _funs_arr;
}

@end
